const {defineConfig} = require('@vue/cli-service')
const path = require("path");
const resolve = (dir) => path.join(__dirname, dir);
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩， 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩， 按需写入
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
//压缩代码并去掉console
const TerserPlugin = require('terser-webpack-plugin');

// 版本号控制
const webpack = require('webpack');
const packageJson = require('./package.json');


module.exports = defineConfig({
  publicPath: "./",
  indexPath: "index.html", // 相对于打包路径index.html的路径
  transpileDependencies: true,
  // assetsDir: 'static',
  productionSourceMap: false,
  outputDir: process.env.outputDir,    // 打包生成目录
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: {
      // 修改打包后css文件名   // css打包文件，添加时间戳
      filename: `static/css/[name].${process.env.NODE_ENV == 'test'?packageJson.testversion:packageJson.proversion}.css`,
      chunkFilename: `static/css/[name].${process.env.NODE_ENV == 'test'?packageJson.testversion:packageJson.proversion}.css`
    }
  },
  chainWebpack: config => {
    config.resolve.symlinks(true); // 修复热更新失效
    config.plugin("html").tap((args) => {
      // 修复 Lazy loading routes Error
      args[0].title = 'web-杂七杂八属性'
      args[0].chunksSortMode = "none";
      return args;
    })
    config.resolve.alias
        .set('@', resolve('src'))
        .set('@assets', resolve('src/assets'))
        .set('@components', resolve('src/components'))
  },
  configureWebpack: config => {
    // 开启 gzip 压缩
    // 需要 npm i -D compression-webpack-plugin
    const plugins = [];
    if (process.env.NODE_ENV == 'test') {
      console.log("packageJson.testversion",packageJson.testversion)
      // 使用 DefinePlugin 注入版本号
      plugins.push(new webpack.DefinePlugin({
        // 将版本号注入到变量中
        'process.env.APP_VERSION': JSON.stringify(packageJson.testversion),
      }))
      // config.output= {
      //   filename: `static/js/[name].${packageJson.testversion}.js`,
      //   chunkFilename: `static/js/[name].${packageJson.testversion}.js`
      // }
    }
    // 正式环境
    if (IS_PROD) {
      // 使用 DefinePlugin 注入版本号
      plugins.push(new webpack.DefinePlugin({
        // 将版本号注入到变量中
        'process.env.APP_VERSION': JSON.stringify(packageJson.proversion),
      }))
      // 开启代码压缩
      plugins.push(
          new CompressionWebpackPlugin({
            filename: "[path][base].gz",
            algorithm: "gzip",
            test: productionGzipExtensions,
            threshold: 10240,
            minRatio: 0.8
          })
      );

      //移除console
      plugins.push(
          new TerserPlugin({
            terserOptions: {
              ecma: undefined,
              warnings: false,
              parse: {},
              compress: {
                drop_console: true,
                drop_debugger: false,
                pure_funcs: ['console.log'] // 移除console
              }
            },
          })
      );
    }
    config.plugins = [...config.plugins, ...plugins];
  },
  configureWebpack: {
    output: {
      filename: `static/js/[name].${packageJson.proversion}.js`,
      chunkFilename: `static/js/[name].${packageJson.proversion}.js`,
    },
  },
  devServer: {
    client: {
      overlay: {
        warnings: true,
        errors: true,
      },
    },
    host: "0.0.0.0",
    port: 8006, // 端口号
    https: false, // https:{type:Boolean}
    open: false, //配置自动启动浏览器
    hot: true, // 热更新
    proxy: {}
  }
})
